package com.yupi.project.service.impl;

import com.yupi.project.service.FileService;
import com.yupi.yuapicommon.model.common.BaseResponse;
import com.yupi.yuapicommon.model.common.BusinessException;
import com.yupi.yuapicommon.model.common.ErrorCode;
import com.yupi.yuapicommon.model.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    private final String LOCAL_DIR = "/usr/share/nginx/images/";

    @Override
    public BaseResponse<String> fileUpload(MultipartFile uploadFile) {
        //1.判断文件是否为图片类型
        String fileName = uploadFile.getOriginalFilename();
        fileName = fileName.toLowerCase(); //解决文件名后缀是大写的
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")) {
            //表示不满足规则
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "图片格式不支持，仅支持jpg、png、gif");
        }
        //2.判断是否为恶意程序,转化成为图片对象
        String imgFileName = null;
        try {
            BufferedImage bufferedImage =
                    ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width==0||height==0) {
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "图片对象数据不符合要求");
            }

            //3.实现份文件存储 按照yyyy/MM/dd
            String dateDir =
                    new SimpleDateFormat("yyyy/MM/dd/")
                            .format(new Date());
            String fileDirPath = LOCAL_DIR +dateDir;
            File dirFile = new File(fileDirPath);
            if(!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //4.生成文件防止重名 name.type
            int index = fileName.lastIndexOf(".");
            String fileType =
                    fileName.substring(index);
            String uuid = UUID.randomUUID().toString();
            //拼接文件名称
            String realFileName = uuid+fileType;
            //5.文件实现上传
            uploadFile.transferTo(new File(fileDirPath+realFileName));
            //暂时使用网络地址代替真正的url地址
            imgFileName = dateDir + realFileName;
            log.info("本地文件地址：==>" + fileDirPath+realFileName);
        } catch (IOException e) {
            log.error("图片上传失败==>",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片上传失败");
        }
        String imgUrl = "http://39.108.117.235/localImage/" + imgFileName;
        log.info("图片url: " + imgUrl);
        return ResultUtils.success(imgUrl);
    }

    @Override
    public BaseResponse<String> fileUploadLocal(MultipartFile uploadFile) {
        String test_dir = "C:/java/img/";
        //1.判断文件是否为图片类型
        String fileName = uploadFile.getOriginalFilename();
        fileName = fileName.toLowerCase(); //解决文件名后缀是大写的
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")) {
            //表示不满足规则
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "图片格式不支持，仅支持jpg、png、gif");
        }
        //2.判断是否为恶意程序,转化成为图片对象
        String imgFileName = null;
        try {
            BufferedImage bufferedImage =
                    ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width==0||height==0) {
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "图片对象数据不符合要求");
            }

            //3.实现份文件存储 按照yyyy/MM/dd
            String dateDir =
                    new SimpleDateFormat("yyyy/MM/dd/")
                            .format(new Date());
            //E:/java/img/yyyy/MM/dd
            String fileDirPath = test_dir +dateDir;
            File dirFile = new File(fileDirPath);
            if(!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //4.生成文件防止重名 name.type
            int index = fileName.lastIndexOf(".");
            String fileType =
                    fileName.substring(index);
            String uuid = UUID.randomUUID().toString();
            //拼接文件名称
            String realFileName = uuid+fileType;
            //5.文件实现上传
            uploadFile.transferTo(new File(fileDirPath+realFileName));
            //暂时使用网络地址代替真正的url地址
            imgFileName = dateDir + realFileName;
            log.info("本地文件地址：==>" + fileDirPath+realFileName);
        } catch (IOException e) {
            log.error("图片上传失败==>",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片上传失败");
        }
        String imgUrl = "http://39.108.117.235/localImage/" + imgFileName;
        log.info("图片url: " + imgUrl);
        return ResultUtils.success(imgUrl);
    }

}
